'use strict';
const jwt = require('jsonwebtoken');

const authenticationList = [
  '/api/info',
];

// app/middleware/error_handler.js
module.exports = () => {
  return async function errorHandler(ctx, next) {
    const token = ctx.cookies.get('token');
    console.log(ctx.request.path);
    try {
      if (authenticationList.indexOf(ctx.request.path) !== -1) {
        const user = jwt.verify(token, 'liuyu000');
        ctx.userInfo = user;
        await next();
      } else {
        await next();
      }
    } catch (e) {
      if (token) {
        ctx.throw(401, '登录失效请重写登录');
      } else {
        ctx.throw(401, '用户未登录');
      }
    }
  };
};
